package com.carlyang.jspservlet.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.carlyang.jspservlet.dao.UserDao;
import com.carlyang.jspservlet.model.User;
import com.carlyang.jspservlet.util.DbUtil;

public class LoginServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	DbUtil dbUtil = new DbUtil();
	UserDao userDao = new UserDao();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		this.doPost(request, response);//get请求交给Post处理
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		//获取客户端表单提交过来的用户登录数据
		String userName = request.getParameter("userName");
		String password = request.getParameter("pwd");
		String remember = request.getParameter("remember");
		System.out.println("remember:"+remember);
		response.setCharacterEncoding("gbk");//gbk必须小写才能显示中文，大写GBK请求时会报错
		PrintWriter out = response.getWriter();
		if ("".equals(userName) || "".equals(password) ||userName == null || password ==null) {
			System.out.println("没有参数！");
			out.println("没有参数");
			response.sendRedirect("login.jsp");//客户端跳转/重定向
			out.close();
			return;
		}
		Connection con = null;
		try {
			User user = new User(userName, password);
			System.out.println(user);
			con = dbUtil.getCon();
			User currentUser = userDao.login(con, user);//登录验证
			if (currentUser == null) {
				System.out.println("未查询到用户！");
				out.println("未查询到用户！");
				request.setAttribute("error", "用户名或密码错误");
				request.setAttribute("userName", userName);
				request.setAttribute("pwd", password);
				request.getRequestDispatcher("login.jsp").forward(request, response);//服务器跳转/转发
			}else {
				System.out.println("查询到用户！");
				out.println("查询到用户！");
				HttpSession session = request.getSession();
				session.setAttribute("currentUser", currentUser);
				response.sendRedirect("main.jsp");//客户端跳转/重定向
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			// TODO Auto-generated catch block
			try {
				if (con!=null) {
					dbUtil.closeCon(con);
				}
				out.close();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
}
